// pages/login/login.ts
import api from '../../api/index';
import { authManager } from '../../api/auth-manager';
const i18n = require('../../i18n/index');

// 获取应用实例
const app = getApp<IAppOption>();

interface LoginPageData {
  loading: boolean;
  redirect: string | null;
  privacyChecked: boolean;
  showPrivacyTip: boolean;
  // 🎯 公众号相关状态
  fromOfficialAccount: boolean;  // 是否来自公众号
  hasOfficialOpenid: boolean;    // 是否已获取公众号openid
  needPhoneAuth: boolean;        // 是否需要手机号授权
  // i18n 文案
  l10n: any;
}

Page({
  data: {
    loading: false,
    redirect: null,
    privacyChecked: false,
    showPrivacyTip: false,
    fromOfficialAccount: false,
    hasOfficialOpenid: false,
    needPhoneAuth: false,
    l10n: {
      back: '', appName: '', subtitle: '', welcome: '', loginTip: '', wechatBtn: '', loggingIn: '', guestBtn: '',
      privacyPrefix: '', privacyLink: '', privacyTip: '', officialDone: ''
    }
  } as LoginPageData,

  langUnsub: null as (() => void) | null,

  /**
   * 页面加载
   */
  onLoad(options: any) {
    console.log('[LoginPage] 页面加载，参数:', options);

    // 初始化多语言
    this.updateTexts();
    this.langUnsub = i18n.onLangChange(() => this.updateTexts());
    
    // 🆕 检查是否通过 from=official 参数进入
    if (options.from === 'official') {
      console.log('[LoginPage] ✅ 检测到来自公众号参数 from=official');
      wx.setStorageSync('fromOfficialAccount', true);
    }
    
    // 检查是否从webview-auth页面跳转而来
    if (options.fromWebViewAuth) {
      const officialAccountOpenid = options.officialAccountOpenid;
      const unionid = options.unionid;
      const hasUnionid = !!unionid;
      
      console.log('[LoginPage] ⭐ 从webview-auth页面跳转而来，详细参数:', {
        officialAccountOpenid: officialAccountOpenid ? this.maskString(officialAccountOpenid) : null,
        fromWebViewAuth: options.fromWebViewAuth,
        fromOfficialAccount: options.fromOfficialAccount,
        hasUnionid
      });
      
      if (officialAccountOpenid) {
        console.log('[LoginPage] ✅ 从webview-auth返回，获取到公众号openid:', officialAccountOpenid);
        
        // 存储公众号openid
        wx.setStorageSync('officialAccountOpenid', officialAccountOpenid);
        
        if (unionid) {
          console.log('[LoginPage] ✅ 从webview-auth返回，获取到unionid:', unionid);
          wx.setStorageSync('unionid', unionid);
        }
      }
    }
    
    // 🆕 恢复用户之前的隐私政策同意状态
    this.restorePrivacyState();
    
    // 检查是否来自公众号
    this.checkFromOfficialAccount();
    
    // 保存重定向信息
    if (options?.redirect) {
      this.setData({ redirect: options.redirect });
    }
  },

  onShow() {
    console.log('[LoginPage] 页面显示');
    // 刷新多语言
    this.updateTexts();
    
    // 延迟检查公众号状态，确保首页的存储操作完成
    setTimeout(() => {
      this.checkOfficialAccountStatus();
      // 🆕 检查是否需要自动登录（从webview-auth返回）
      this.checkAutoLogin();
    }, 200);
    
    // 重置loading状态
    this.setData({ loading: false });
  },

  onUnload() {
    if (this.langUnsub) { try { this.langUnsub(); } catch (_) {} this.langUnsub = null; }
  },

  updateTexts() {
    const t = (k: string) => i18n.t(`login.${k}`);
    const l10n = {
      back: t('back'), appName: t('appName'), subtitle: t('subtitle'), welcome: t('welcome'), loginTip: t('loginTip'),
      wechatBtn: t('wechatBtn'), loggingIn: t('loggingIn'), guestBtn: t('guestBtn'),
      privacyPrefix: t('privacyPrefix'), privacyLink: t('privacyLink'), privacyTip: t('privacyTip'), officialDone: t('officialDone')
    };
    this.setData({ l10n });
    try { wx.setNavigationBarTitle({ title: t('title') }); } catch (e) {}
  },

  /**
   * 🆕 检查公众号状态
   */
  checkOfficialAccountStatus() {
    const allStorage = wx.getStorageInfoSync();
    console.log('[LoginPage] 🔍 当前存储键列表:', allStorage.keys);
    
    const fromOfficialAccount = wx.getStorageSync('fromOfficialAccount') || false;
    const officialAccountOpenid = wx.getStorageSync('officialAccountOpenid');
    
    console.log('[LoginPage] 🔍 检查公众号状态:', {
      fromOfficialAccount,
      hasOpenid: !!officialAccountOpenid,
      openid: officialAccountOpenid ? 'o***' + officialAccountOpenid.slice(-4) : null,
      rawFromOfficial: wx.getStorageSync('fromOfficialAccount')
    });
    
    this.setData({
      fromOfficialAccount,
      hasOfficialOpenid: !!officialAccountOpenid,
      needPhoneAuth: fromOfficialAccount && !!officialAccountOpenid
    });
  },

  /** 🆕 恢复用户之前的隐私政策同意状态 */
  restorePrivacyState() {
    const privacyAgreedBefore = wx.getStorageSync('privacyAgreedBefore') || false;
    console.log('[LoginPage] 🔄 恢复隐私政策状态:', { privacyAgreedBefore });
    if (privacyAgreedBefore) {
      this.setData({ privacyChecked: true, showPrivacyTip: false });
      console.log('[LoginPage] ✅ 已恢复用户之前同意的隐私政策状态');
    }
  },

  /** 🆕 检查是否需要自动登录 */
  checkAutoLogin() {
    console.log('[LoginPage] 🔍 检查是否需要自动登录');
    const justFromWebViewAuth = wx.getStorageSync('justFromWebViewAuth');
    const fromOfficialAccount = this.data.fromOfficialAccount;
    const hasOfficialOpenid = this.data.hasOfficialOpenid;
    const privacyAgreedBefore = wx.getStorageSync('privacyAgreedBefore') || false;
    console.log('[LoginPage] 🔍 自动登录检查条件:', { justFromWebViewAuth, fromOfficialAccount, hasOfficialOpenid, privacyAgreedBefore });
    if (justFromWebViewAuth && fromOfficialAccount && hasOfficialOpenid && privacyAgreedBefore) {
      console.log('[LoginPage] ✅ 满足自动登录条件，开始自动登录流程');
      wx.removeStorageSync('justFromWebViewAuth');
      this.setData({ privacyChecked: true, showPrivacyTip: false });
      setTimeout(() => {
        console.log('[LoginPage] 🚀 开始自动登录...');
        wx.showToast({ title: i18n.t('login.autoLoggingInToast'), icon: 'loading', duration: 2000 });
        this.unifiedLogin({ detail: null });
      }, 800);
    } else if (justFromWebViewAuth && fromOfficialAccount && hasOfficialOpenid && !privacyAgreedBefore) {
      console.log('[LoginPage] ⚠️ 从webview-auth返回但用户未曾同意隐私政策，需要用户手动操作');
      wx.removeStorageSync('justFromWebViewAuth');
      wx.showToast({ title: i18n.t('login.privacyToast'), icon: 'none', duration: 2000 });
      this.setData({ showPrivacyTip: true });
      setTimeout(() => { this.setData({ showPrivacyTip: false }); }, 3000);
    } else {
      console.log('[LoginPage] ℹ️ 不满足自动登录条件，需要用户手动操作');
      wx.removeStorageSync('justFromWebViewAuth');
    }
  },

  /** 跳转到公众号授权页面 */
  goToOfficialAccountAuth() {
    console.log('[LoginPage] 🎯 跳转到公众号授权页面获取openid');
    wx.navigateTo({
      url: '/pages/webview-auth/webview-auth',
      fail: (error) => {
        console.error('[LoginPage] ❌ 跳转到公众号授权页面失败:', error);
        this.showToast(i18n.t('login.jumpFailed'));
      }
    });
  },

  /** 🆕 开始微信登录流程 */
  async startWechatLogin() {
    console.log('[LoginPage] 🚀 开始微信登录流程');
    if (!this.data.privacyChecked) {
      console.log('[LoginPage] ⚠️ 隐私政策未同意');
      this.setData({ showPrivacyTip: true });
      return;
    }
    if (this.data.fromOfficialAccount) {
      if (this.data.hasOfficialOpenid) {
        console.log('[LoginPage] ✅ 已有公众号openid，切换到手机号授权模式');
        this.setData({ needPhoneAuth: true });
        wx.showToast({ title: i18n.t('login.needPhoneAuth'), icon: 'none', duration: 2000 });
      } else {
        console.log('[LoginPage] ⚠️ 未获取公众号openid，先跳转授权');
        wx.showToast({ title: i18n.t('login.needOAAuth'), icon: 'none', duration: 1500 });
        setTimeout(() => { this.goToOfficialAccountAuth(); }, 1500);
      }
    } else {
      console.log('[LoginPage] 📱 普通用户，切换到手机号授权模式');
      this.setData({ needPhoneAuth: true });
      wx.showToast({ title: i18n.t('login.needPhoneAuth'), icon: 'none', duration: 2000 });
    }
  },

  /** 统一登录流程 */
  async unifiedLogin(e: any) {
    console.log('[LoginPage] 🚀 开始统一登录流程');
    try {
      const cachedUnionid = wx.getStorageSync('unionid');
      console.log('[LoginPage] 🔍 检查是否获取到 unionid:', cachedUnionid ? '已获取' : '未获取到');
      if (this.data.fromOfficialAccount && !this.data.hasOfficialOpenid) {
        console.log('[LoginPage] ⚠️ 来自公众号但未获取openid，先跳转授权');
        this.goToOfficialAccountAuth();
        return;
      }
      const { code } = await wx.login();
      if (!code) {
        console.error('[LoginPage] ❌ 微信code获取失败');
        this.showToast(i18n.t('login.wxCodeFailed'));
        return;
      }
      console.log('[LoginPage] ✅ 微信code获取成功');
      let userInfo: any = null;
      try {
        const userInfoRes = await wx.getUserInfo({ lang: 'zh_CN', desc: '用于完善会员资料' });
        userInfo = userInfoRes;
        console.log('[LoginPage] ✅ 获取用户信息成功');
      } catch (userInfoError) {
        console.warn('[LoginPage] ⚠️ 获取用户信息失败，继续登录流程');
      }
      let phoneInfo = null;
      if (e && e.detail) {
        phoneInfo = e.detail;
        console.log('[LoginPage] 📱 获取到手机号授权信息');
      }
      const loginData: any = {
        code,
        encryptedData: phoneInfo?.encryptedData || userInfo?.encryptedData || '',
        iv: phoneInfo?.iv || userInfo?.iv || '',
        create_if_not_exists: true,
        needUnionId: true
      };
      if (this.data.fromOfficialAccount && this.data.hasOfficialOpenid) {
        console.log('[LoginPage] 🔗 准备绑定公众号openid到用户wx_openid字段');
        const officialAccountOpenid = wx.getStorageSync('officialAccountOpenid');
        loginData.fromOfficialAccount = true;
        loginData.officialAccountOpenid = officialAccountOpenid;
        if (cachedUnionid) {
          loginData.unionid = cachedUnionid;
          console.log('[LoginPage] ✅ 从缓存获取到unionid，添加到登录请求');
        }
      }
      const launchScene = wx.getStorageSync('launchScene') || '';
      loginData.launchScene = launchScene;
      console.log('[LoginPage] 📤 发送登录请求数据:', JSON.stringify(loginData));
      const res = await api.wechatPhoneLogin(loginData);
      console.log('[LoginPage] ✅ 登录请求成功，状态码:', res.statusCode);
      await this.handleLoginResponse(res, phoneInfo);
    } catch (error: any) {
      console.error('[LoginPage] ❌ 登录失败:', error);
      this.showToast(error.message || i18n.t('login.loginFailed'));
    }
  },
  
  /** 显示错误提示 */
  showToast(message: string) {
    wx.showToast({ title: message, icon: 'none', duration: 2000 });
  },
  
  /** 对敏感字符串进行脱敏处理 */
  maskString(str: string): string {
    if (!str) return '';
    if (str.length <= 8) return str.substring(0, 1) + '***' + str.substring(str.length - 1);
    return str.substring(0, 3) + '****' + str.substring(str.length - 3);
  },

  /** 游客登录 */
  guestLogin() {
    console.log('[LoginPage] 游客模式登录');
    wx.showToast({ title: i18n.t('login.guestEntering'), icon: 'success', duration: 1500 });
    wx.setStorageSync('isGuestMode', true);
    setTimeout(() => { wx.switchTab({ url: '/pages/index/index' }); }, 1500);
  },

  /** 获取微信登录code */
  async getWechatCode(): Promise<string> {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => { if (res.code) resolve(res.code); else reject(new Error(i18n.t('login.wxCodeFailed'))); },
        fail: reject
      });
    });
  },

  /** 获取用户信息（用于unionid）*/
  async getUserProfile(): Promise<any> {
    try {
      return new Promise((resolve) => {
        wx.getUserProfile({
          desc: '用于完善用户资料',
          success: (res) => {
            console.log('[LoginPage] ✅ 获取用户信息成功');
            resolve({
              nickname: res.userInfo.nickName,
              avatar: res.userInfo.avatarUrl,
              gender: res.userInfo.gender,
              country: res.userInfo.country,
              province: res.userInfo.province,
              city: res.userInfo.city
            });
          },
          fail: (error) => {
            console.log('[LoginPage] ⚠️ 获取用户信息失败，继续登录流程');
            resolve(null);
          }
        });
      });
    } catch (error) {
      console.log('[LoginPage] ⚠️ getUserProfile API不可用，跳过用户信息获取');
      return null;
    }
  },

  /** 处理登录响应 */
  async handleLoginResponse(res: any, phoneInfo?: any) {
    console.log('[LoginPage] 🔍 处理登录响应');
    if (!res || !res.data || res.statusCode !== 200) {
      console.error('[LoginPage] ❌ 登录响应无效:', res);
      this.showToast(i18n.t('login.loginFailed'));
      return;
    }
    console.log('[LoginPage] ✅ 登录验证成功');
    const responseData = res.data.data || res.data;
    const { token, userId, openid, unionid, nickname, phone } = responseData;
    if (unionid) wx.setStorageSync('unionid', unionid);
    console.log('[LoginPage] 📋 登录成功，用户信息:', { userId, openid: openid ? this.maskString(openid) : null });
    await authManager.login({
      user: {
        id: Number(userId),
        username: nickname || 'user_' + userId,
        nickname: nickname,
        isActive: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      token: { token: token, expiresAt: Date.now() + 24 * 60 * 60 * 1000, tokenType: 'Bearer' }
    });
    const updateData: any = {};
    let needUpdate = false;
    const userUnionid = unionid || responseData.union_id || responseData.unionId || wx.getStorageSync('unionid');
    if (userUnionid && !responseData.unionid) { updateData.unionid = userUnionid; needUpdate = true; }
    const userPhone = phone || responseData.phone;
    const hasPhoneInfo = phoneInfo && phoneInfo.encryptedData && phoneInfo.iv;
    if (hasPhoneInfo && !userPhone) { updateData.encryptedData = phoneInfo.encryptedData; updateData.iv = phoneInfo.iv; needUpdate = true; }
    if (needUpdate) {
      try {
        if (this.data.fromOfficialAccount && this.data.hasOfficialOpenid) {
          const officialAccountOpenid = wx.getStorageSync('officialAccountOpenid');
          if (officialAccountOpenid) updateData.wxOpenid = officialAccountOpenid;
        }
        await api.updateUserProfile(updateData);
      } catch (error) {
        console.error('[LoginPage] ❌ 更新用户信息请求失败:', error);
      }
    }
    wx.switchTab({ url: '/pages/index/index' });
  },

  /** 登录成功处理 */
  handleLoginSuccess() {
    this.setData({ loading: false, needPhoneAuth: false });
    setTimeout(() => {
      const redirect = this.data.redirect;
      if (redirect) {
        const tabPages = ['index', 'stats', 'water', 'device', 'profile'];
        if (tabPages.includes(redirect)) {
          wx.switchTab({ url: `/pages/${redirect}/${redirect}` });
        } else {
          wx.navigateTo({ url: `/pages/${redirect}/${redirect}` });
        }
      } else {
        wx.switchTab({ url: '/pages/index/index' });
      }
    }, 1500);
  },

  /** 切换隐私政策勾选状态*/
  togglePrivacyChecked() {
    const newCheckedState = !this.data.privacyChecked;
    this.setData({ privacyChecked: newCheckedState, showPrivacyTip: false });
    if (newCheckedState) wx.setStorageSync('privacyAgreedBefore', true);
  },

  /** 跳转到隐私政策页面*/
  navigateToPrivacy() {
    wx.navigateTo({ url: '/pages/privacy/privacy' });
  },

  /** 返回首页 */
  goToIndex() {
    wx.switchTab({ url: '/pages/index/index' });
  },

  /** 检查是否来自公众号 */
  checkFromOfficialAccount() {
    const fromOfficialParam = wx.getStorageSync('fromOfficialAccount');
    const fromOfficialCache = wx.getStorageSync('fromOfficialAccount');
    if (fromOfficialParam || fromOfficialCache) {
      console.log('[LoginPage] 🎯 检测到来自公众号');
      wx.setStorageSync('fromOfficialAccount', true);
      const cachedOpenid = wx.getStorageSync('officialAccountOpenid');
      this.setData({ fromOfficialAccount: true, hasOfficialOpenid: !!cachedOpenid, needPhoneAuth: !!cachedOpenid });
    }
  }
});
